package com.hsmw.api.controller.driver;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.controller.pub.WebSocket;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.*;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 *  司机端上报
 * </p>
 *
 * @author xc
 * @since 2021-07-15
 */
@RestController
@RequestMapping("/api/report")
@Api(tags = "DRIVER-司机上报信息API")
public class HsmwReportController extends BaseController<HsmwReportService, HsmwReport>{




    @Autowired
    private HsmwReportService hsmwReportService;

    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;



    @Autowired
    private HsmwVehicleMapper hsmwVehicleMapper;

    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

    @Autowired
    private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;

    @Autowired
    private HsmwOrderService hsmwOrderService;

    @Autowired
    private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper;

    @Autowired
    private HsmwItemMapper hsmwItemMapper;

    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private HsmwPushInfoService hsmwPushInfoService;

    @Autowired
    private HsmwPictureService hsmwPictureService;


    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;



    @Autowired
    private HsmwTpspUserService hsmwTpspUserService;




    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.driverOrderCanceled}")
    private int driverOrderCanceled;



    @Log(title = "司机端：上报信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "上报信息新增修改接口", notes = "上报信息新增修改接口", produces = "application/json")
    @PostMapping("reportSaveOrUpdate")
    public DataResponse reportSaveOrUpdate(@RequestBody HsmwReport hsmwReport){

        hsmwReportService.reportSaveOrUpdate(hsmwReport);

        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }



    @ApiOperation(value = "获取上报信息列表", notes = "获取上报信息列表", produces = "application/json")
    @PostMapping("/getHsmwOrderPage")
    public DataResponse findReportListInfo(@RequestBody @Valid BasePage<HsmwReport> basePage) {
        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        HsmwReport hsmwReport = basePage.getRequestData();
        IPage<HsmwReport> data = hsmwReportService.findReportListInfo(page, hsmwReport);
        for (HsmwReport record : data.getRecords()) {
            String vehicleId = record.getVehicleId();
            String driId = record.getDriId();
            HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
            if(hsmwVehicle != null){
                record.setVehicleNum(hsmwVehicle.getVehiclePlate());
            }

            List<HsmwPicture> hsmwPictures = hsmwPictureService.list(new LambdaQueryWrapper<HsmwPicture>().eq(HsmwPicture::getPortId, record.getId() ));
            record.setHsmwPictures(hsmwPictures);

            HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectById(driId);
            if(hsmwUserDriver != null){
                record.setMyPicture(hsmwUserDriver.getMyPicture());
            }

        }
        return new DataResponse(data);
    }



    @ApiOperation(value = "根据id获取上报信息", notes = "根据id获取上报信息", produces = "application/json")
    @ApiImplicitParam(value = "上报id", name = "reportId",dataType = "String")
    @PostMapping("reportId")
    public DataResponse findReportInfoById(String reportId){

        return new DataResponse(hsmwReportService.findReportInfoById(reportId));
    }



    @ApiOperation(value = "根据司机id获取请假信息", notes = "根据司机id获取请假信息", produces = "application/json")
    @ApiImplicitParam(name = "司机id", value = "id",dataType = "String")
    @PostMapping("findReportInfoByDriverId")
    public DataResponse findReportInfoByDriverId(String id){

        return new DataResponse(hsmwReportService.findReportInfoByDriverId(id));
    }


    @ApiOperation(value = "根据司机id获取最新的上报信息", notes = "根据司机id获取最新的上报信息", produces = "application/json")
    @ApiImplicitParam(name = "司机id", value = "id",dataType = "String")
    @PostMapping("findReportNewInfoByDriverId")
    public DataResponse findReportNewInfoByDriverId(String id){

        HsmwReport hsmwReport = hsmwReportService.findReportNewInfoByDriverId(id);
        return new DataResponse(hsmwReport);
    }



    @ApiOperation(value = "提前工作", notes = "提前工作", produces = "application/json")
    @ApiImplicitParam(name = "上报id", value = "id",dataType = "String")
    @PostMapping("DriverAdvanceWork")
    public DataResponse DriverAdvanceWork(String id){

        HsmwReport hsmwReport = hsmwReportService.getById(id);
        hsmwReport.setEndTime(LocalDate.now());
        hsmwReport.setAdvanceFlag("1");
        hsmwReportService.updateById(hsmwReport);
        String driId = hsmwReport.getDriId();
        HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectById(driId);
        hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
        hsmwUserDriverMapper.updateById(hsmwUserDriver);
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }

    @ApiOperation(value = "取消请假", notes = "取消请假", produces = "application/json")
    @ApiImplicitParam(value = "上报id", name = "id",dataType = "String")
    @PostMapping("deleteReportById")
    public DataResponse deleteReportById(String id){

        return new DataResponse(hsmwReportService.removeById(id));
    }



    @ApiOperation(value = "第三方待解决问题列表", notes = "第三方待解决问题列表", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "条件查询传递参数",dataType = "String"),
            @ApiImplicitParam(name = "exType",value = "审核状态 待解决列表：1，已解决列表：2",dataType = "String")
    })
    @PostMapping("findReportToSolveStatusList")
    public DataResponse findReportToSolveStatusList(String name,String exType){

        return new DataResponse(hsmwReportService.findReportToSolveStatusList(name,exType));
    }


    @ApiOperation(value = "待解决问题详情", notes = "待解决问题详情", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reId",value = "上报id",dataType = "String",required = true),
            @ApiImplicitParam(name = "exType",value = "审核状态 待解决列表：1，已解决列表：2",dataType = "String")
    })
    @PostMapping("findReportInfoByRepostId")
    public DataResponse findReportInfoByRepostId(String reId,String exType){



        return new DataResponse(hsmwReportService.findReportInfoByRepostId(reId,exType));
    }


  /*  @ApiOperation(value = "同意或者不同意司机请假 同意：2 不同意：3", notes = "同意或者不同意司机请假", produces = "application/json")
    @PostMapping("updateReportExStatus")
    public DataResponse updateReportExStatus(@RequestBody HsmwReport hsmwReport){

        if(StringUtils.isNull(hsmwReport)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数错误");
        }

        return hsmwReportService.updateReportExStatus(hsmwReport);
    }*/


    @ApiOperation(value = "第三方查询个人信息", notes = "第三方查询个人信息", produces = "application/json")
    @PostMapping("findTPSPInfoById")
    public DataResponse findTPSPInfoById(){
        ForemanInformationVo foremanInformationVo = new ForemanInformationVo();
        HsmwTpspUser currentFormanHsmwUser = currentHsmwUserUtils.getCurrentTpspUserInfo();
        if(currentFormanHsmwUser != null){
            foremanInformationVo.setAvatar(currentFormanHsmwUser.getAvatar());
            foremanInformationVo.setUserPhone(currentFormanHsmwUser.getUsername());
            foremanInformationVo.setUserName(currentFormanHsmwUser.getName());
            foremanInformationVo.setUserId(currentFormanHsmwUser.getId());
        }
        return new DataResponse(foremanInformationVo);
    }


    @ApiOperation(value = "新增或修改第三方信息", notes = "新增或修改user信息", produces = "application/json")
    @PostMapping("saveOrUpdateUser")
    public DataResponse saveOrUpdateUser(@RequestBody HsmwTpspUser hsmwUser){

        if(hsmwUser != null){
            if(StringUtils.isNotBlank(hsmwUser.getId())){
                List<HsmwTpspUser> list = hsmwTpspUserService.list();
                for (HsmwUser user : list) {
                    if(StringUtils.equals(user.getUsername(),hsmwUser.getUsername())){
                        System.err.println(hsmwUser.getUsername());
                        return new DataResponse<>(CommonConstants.ResponseStatus.FAIL,"手机号重复");
                    }
                }
            }
            hsmwTpspUserService.updateById(hsmwUser);
        }
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }

   /* @ApiOperation(value = "重新派车", notes = "重新派车", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String"),
            @ApiImplicitParam(name = "type",value = "问题类型",dataType = "String")
    })
    @PostMapping("resendTheCar")
    public DataResponse resendTheCar(String id,String type) {

        if (StringUtils.isBlank(id)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误，id不可为空");
        }
        HsmwUserDriver driver = hsmwUserDriverMapper.selectById(id);
        HashMap param = new HashMap();
        param.put("vehicleId", driver.getVehicleId());
        List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
        if(CollectionUtil.isEmpty(orderList)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"没有订单，无需重新派车");
        }
        for (CurrentOrderInfoVO currentOrderInfoVO : orderList) {
            // 需求id
            String orderVehicleRequestId = currentOrderInfoVO.getOrderVehicleRequestId();
            HsmwOrderVehicleRequest orderVehicleRequest = hsmwOrderVehicleRequestService.getById(orderVehicleRequestId);

            // 项目id
            String itemId = currentOrderInfoVO.getItemId();
            // 根据项目id 查询项目的经纬度信息，然后查询车辆信息 找到最近的车辆
            HsmwItem hsmwItem = hsmwItemMapper.selectById(itemId);
            // 获取子订单id 查询对应的子订单信息
            String orderVehicleRelationId = currentOrderInfoVO.getOrderVehicleRelationId();
            HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationMapper.selectById(orderVehicleRelationId);

            //根据车辆类型 型号 项目所在位置经纬度 查询空闲中的车辆
            QueryFreeParams queryFreeParams = new QueryFreeParams();
            queryFreeParams.setVehicleModel(orderVehicleRequest.getVehicleModel());
            queryFreeParams.setVehicleType(orderVehicleRequest.getVehicleType());

            List<IdleVehicleVo> vehicleVoList = hsmwVehicleMapper.findVehicleList(queryFreeParams);
            if (CollectionUtil.isNotEmpty(vehicleVoList)) {
                List<Map<String, Object>> vehilceList = new ArrayList<>();
                for (IdleVehicleVo hsmwVehicle : vehicleVoList) {
                    String vehicleLocalteInfo = null;
                    String destinationLocateInfo = hsmwItem.getLng() + "," + hsmwItem.getLat();
                    if (com.htn.common.core.utils.StringUtils.isNotBlank(hsmwVehicle.getImeiNum())) {
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum());
                        if (com.htn.common.core.utils.StringUtils.isNotNull(entity) && com.htn.common.core.utils.StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }
                    }
                    HashMap calculateParam = new HashMap();
                    calculateParam.put("origin", vehicleLocalteInfo);
                    calculateParam.put("destination", destinationLocateInfo);
                    Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
                    Map map = new HashMap();
                    map.put("time", durationTime);
                    map.put("vehicle", hsmwVehicle);
                    vehilceList.add(map);

                }
                Collections.sort(vehilceList, new Comparator<Map<String, Object>>() {
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        Integer name1 = Integer.valueOf(o1.get("time").toString());
                        Integer name2 = Integer.valueOf(o2.get("time").toString());
                        return name1.compareTo(name2);
                    }
                });
                for (Map<String, Object> map : vehilceList) {
                    System.out.println("time:" + map.get("time") + " vehicle:" + map.get("vehicle"));
                }
                Map<String, Object> map = vehilceList.get(0);
                Long time = (Long) map.get("time")/60;
                time = time + 10;
                IdleVehicleVo vehicle = (IdleVehicleVo) map.get("vehicle");

                //修改子订单状态
                relation.setOrderStatus(ChildOrderStatusEnum.UNDERREVIEW.getValue());
                hsmwOrderVehicleRelationMapper.updateById(relation);
                HsmwHtnUser hsmwUser = hsmwHtnUserService.getById(currentOrderInfoVO.getCreateUser());
                SendSmsUtil.sendDriverSmsCode(appId, appKey, "",driverOrderCanceled, smsSign, hsmwUser.getUsername());
                String msg = "很抱歉，泵车"+vehicle.getVehiclePlate()+" "+vehicle.getVehicleModel()+" "+vehicle.getVehicleType()+" 司机出现问题，无法为您继续服务,订单已经被取消。" +
                        "系统自动为您匹配最近的车辆，预计"+time+"分钟后可以到达，您是否需要重新下单";
                WebSocketReturnVO vo =new WebSocketReturnVO();
                vo.setStatus(WebsocketTypeEnum.REORDER.getValue());
                vo.setMessage(msg);
                vo.setData(orderVehicleRequest);
                vo.setRemaindSeconds(time);
                HsmwPushInfo hsmwPushInfo = new HsmwPushInfo();
                hsmwPushInfo.setDataInfo(orderVehicleRequest.getId());
                hsmwPushInfo.setMessage(msg);
                hsmwPushInfo.setForemanId(orderVehicleRequest.getCreateUser());
                hsmwPushInfo.setReachTime(time);
                hsmwPushInfo.setStatus("0");
                hsmwPushInfoService.save(hsmwPushInfo);
                vo.setPushId(hsmwPushInfo.getId());
                String  returnJson = JSONObject.toJSON(vo).toString();
                if(hsmwUser != null){
                    webSocket.AppointSending(hsmwUser.getUsername(),returnJson);
                    String msgs = "泵车出现问题，无法继续订单，是否需要系统为您自动派单";
                    TencentPushUtils.pushForeManMsg(msgs,hsmwUser.getUsername(),"has_new_message");
                    TencentPushUtils.selfrunMsg(msgs,hsmwUser.getUsername(),"has_new_message");
                }

            }else {

                //修改子订单状态
                relation.setOrderStatus(ChildOrderStatusEnum.UNDERREVIEW.getValue());
                hsmwOrderVehicleRelationMapper.updateById(relation);

                HsmwHtnUser hsmwUser = hsmwHtnUserService.getById(currentOrderInfoVO.getCreateUser());
                SendSmsUtil.sendDriverSmsCode(appId, appKey, "",driverOrderCanceled, smsSign, hsmwUser.getUsername());
                String msg = "很抱歉，暂无可用车辆";
                WebSocketReturnVO vo =new WebSocketReturnVO();
                vo.setStatus(WebsocketTypeEnum.REORDER.getValue());
                vo.setMessage(msg);
                vo.setData(orderVehicleRequest);
                vo.setRemaindSeconds(0);
                HsmwPushInfo hsmwPushInfo = new HsmwPushInfo();
                hsmwPushInfo.setDataInfo(orderVehicleRequest.getId());
                hsmwPushInfo.setMessage(msg);
                hsmwPushInfo.setForemanId(orderVehicleRequest.getCreateUser());
                hsmwPushInfo.setStatus("0");
                hsmwPushInfoService.save(hsmwPushInfo);
                vo.setPushId(hsmwPushInfo.getId());
                String returnJson = JSONObject.toJSON(vo).toString();
                if(hsmwUser != null){
                    webSocket.AppointSending(hsmwUser.getUsername(),returnJson);
                    String msgs = "泵车出现问题，无法继续订单，当前暂无可用车辆，请知晓";
                    TencentPushUtils.pushForeManMsg(msgs,hsmwUser.getUsername(),"has_new_message");
                    TencentPushUtils.selfrunMsg(msgs,hsmwUser.getUsername(),"has_new_message");

                }
            }
        }

        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }*/

    @ApiOperation(value = "根据id获取上报信息-司机端查看详情", notes = "根据id获取上报信息", produces = "application/json")
    @ApiImplicitParam(value = "上报id", name = "reportId",dataType = "String")
    @PostMapping("findReportById")
    public DataResponse findReportById(String reportId){


        return new DataResponse(hsmwReportService.findReportById(reportId));
    }

    @ApiOperation(value = "司机投诉供应商-司机端", notes = "司机投诉供应商-司机端", produces = "application/json")
    @PostMapping("saveOrUpdateDriverComplaints")
    public DataResponse saveOrUpdateDriverComplaints(@RequestBody HsmwDriverComplaints hsmwDriverComplaints){

        return hsmwReportService.saveOrUpdateDriverComplaints(hsmwDriverComplaints);
    }






}

